using System.Reflection;
using System.Security.Claims;
using MediatR;
using Microsoft.AspNetCore.Http;
using Zhaoxi.Zhihu.UseCases.Common.Attributes;
using Zhaoxi.Zhihu.UseCases.Common.Exceptions;
using Zhaoxi.Zhihu.UseCases.Common.Interface;

namespace Zhaoxi.Zhihu.UseCases.Common.Behaviors;

public class AuthorizationBehavior<TRequest,TResponse>(IUser user,IHttpContextAccessor httpContextAccessor):
    IPipelineBehavior<TRequest,TResponse>
    where TRequest:IRequest<TResponse>
{
    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
    {
        var authorizeAttributes=request.GetType().GetCustomAttributes<AuthorizeAttribute>();

        if (authorizeAttributes.Any())
        {
            var userIdFromToken=httpContextAccessor.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            
            if (string.IsNullOrEmpty(userIdFromToken))
                throw new ForbiddenException();


            Console.WriteLine(user.Id!.Value);
            //其他授权逻辑
        }
           
        
        
        
        return await next();
        
    }
}